package com.imooc.controller;

import com.imooc.pojo.Users;
import com.imooc.pojo.bo.ShopcartBO;
import com.imooc.pojo.bo.UserBO;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UserService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.MD5Utils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: HelloController
 * @Package: com.imooc.controller
 * @Description:
 * @Date: 2021/7/5 7:57
 * @Author: sunzheng@beiming.com
 */
@Api(value = "注册登录", tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("/passport")
public class PassportController extends BaseController {

  @Autowired
  private UserService userService;

  @Autowired
  private RedisOperator redisOperator;

  @ApiOperation(value = "判断用户名是否存在", notes = "判断用户名是否存在", httpMethod = "GET")
  @GetMapping("/usernameIsExist")
  public IMOOCJSONResult usernameIsExist(@RequestParam("username") String username) {

    //判断用户名不能为空
    if (StringUtils.isBlank(username)) {
      return IMOOCJSONResult.errorMsg("用户名不能为空!");
    }
    //查找注册的用户名是否存在
    boolean isExist = userService.queryUsernameIsExist(username);
    if (isExist) {
      return IMOOCJSONResult.errorMsg("用户名已经存在!");
    }

    //请求成功，用户名没有重复
    return IMOOCJSONResult.ok();
  }

  @ApiOperation(value = "用户注册", notes = "用户注册", httpMethod = "POST")
  @PostMapping("/regist")
  public IMOOCJSONResult register(@RequestBody UserBO userBO, HttpServletRequest request,
      HttpServletResponse response) {

    String username = userBO.getUsername();
    String password = userBO.getPassword();
    String confirmPassword = userBO.getConfirmPassword();

    //0、判断用户名和密码必须不为空
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils
        .isBlank(confirmPassword)) {
      return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
    }

    //1、查询用户名是否存在
    boolean isExist = userService.queryUsernameIsExist(username);
    if (isExist) {
      return IMOOCJSONResult.errorMsg("用户名已经存在");
    }

    //2、密码长度不能少于6位
    if (password.length() < 6) {
      return IMOOCJSONResult.errorMsg("密码长度不能少于6位");
    }

    //3、判断两次密码是否一致
    if (!password.equals(confirmPassword)) {
      return IMOOCJSONResult.errorMsg("两次密码输入不一致");
    }

    //4、实现注册
    Users userResult = userService.createUser(userBO);

//    userResult = setNullProperty(userResult);

    // TODO 生成token, 存入redis会话
    // 实现用户的redis会话
    UsersVO usersVO = conventUsersVO(userResult);

    CookieUtils.setCookie(request, response, "user",
        JsonUtils.objectToJson(usersVO), true);

    // TODO 同步购物车数据
    synchShopcartData(userResult.getId(),request, response);

    return IMOOCJSONResult.ok();
  }


  /**
   * 注册登录成功后，同步cookie和redis中的数据
   */
  private void synchShopcartData(String userId, HttpServletRequest request,
      HttpServletResponse response) {
    /**
     * 1. redis中无数据，如果cookie中的购物车为空，那么这个时候不做任何处理
     *                  如果cookie中的购物车不为空，此时直接放入redis中
     * 2. redis中有数据，如果购物车中的购物车为空，那么直接把redis中的购物车覆盖本地cookie
     *                  如果cookie中的购物车不为空,如果redis中的某个商品在cookie中存在，则以cookie为主，删除redis中的，
     *                  把cookie中的商品直接覆盖在redis中。（参考京东）
     * 3. 同步到redis中去了以后，覆盖本地cookie购物车中的数据，保证本地购物车的数据是同步的
     */

    // 从redis中获取购物车
    String shopcartJsonRedis = redisOperator.get(FOODIE_SHOPCART + ":" + userId);
    // 从cookie中获取购物车
    String shopcartStrCookie = CookieUtils.getCookieValue(request, FOODIE_SHOPCART, true);

    if (StringUtils.isBlank(shopcartJsonRedis)) {
      // redis中为空，cookie中不为空，直接把cookie中的数据写入redis中
      if (StringUtils.isNoneBlank(shopcartStrCookie)) {
        redisOperator.set(FOODIE_SHOPCART + ":" + userId, shopcartStrCookie);
      }
    }else {
      // redis中不为空，cookie中不为空，合并redis和cookie中的数据（同一商品则由cookie数据覆盖redis数据）
      if (StringUtils.isNotBlank(shopcartStrCookie)) {
        /**
         * 1. 已经存在的，把cookie中对应的数量覆盖redis（参考京东）
         * 2. 该项商品标记为dai删除，统一放入一个待删除的list
         * 3. 从cookie中清理所有的待删除list
         * 4. 合并redis和cookie中的数据
         * 5. 更新到redis和cookie中
         */
        // 为了循环，把String转换成list
        List<ShopcartBO> shopcartListRedis = JsonUtils.jsonToList(shopcartJsonRedis, ShopcartBO.class);
        List<ShopcartBO> shopcartListCookie = JsonUtils.jsonToList(shopcartStrCookie, ShopcartBO.class);

        // 定义一个待删除的list
        List<ShopcartBO> pendingDeleteList = new ArrayList<>();
        for (ShopcartBO redisShopcart : shopcartListRedis) {
          String redisSpecId = redisShopcart.getSpecId();
          for (ShopcartBO cookieShopcart : shopcartListCookie) {
            String cookieSpecId = cookieShopcart.getSpecId();
            if (redisSpecId.equals(cookieSpecId)) {
              // 覆盖购买数据，不累加，（参考京东）
              redisShopcart.setBuyCounts(cookieShopcart.getBuyCounts());
              // 把cookieShopcart放入待删除列表，用于最后的删除与合并
              pendingDeleteList.add(cookieShopcart);
            }
          }
        }
        // 从现有的cookie中删除对应的覆盖过的商品数据
        shopcartListCookie.removeAll(pendingDeleteList);
        // 合并两个list
        shopcartListRedis.addAll(shopcartListCookie);
        // 更新到redis和cookie
        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, JsonUtils.objectToJson(shopcartListRedis), true);
        redisOperator.set(FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartListRedis));
      }else {
        // redis中不为空，cookie中为空，直接把redis覆盖到cookie
        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, shopcartJsonRedis, true);
      }
    }

  }

  @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST")
  @PostMapping("/login")
  public IMOOCJSONResult login(@RequestBody UserBO userBO, HttpServletRequest request,
      HttpServletResponse response) throws Exception {

    String username = userBO.getUsername();
    String password = userBO.getPassword();

    //0、判断用户名和密码必须不为空
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
      return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
    }

    //1、实现登录
    Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));

    if (userResult == null) {
      return IMOOCJSONResult.errorMsg("用户名或者密码不正确");
    }
//    userResult = setNullProperty(userResult);

    // TODO 生成token, 存入redis会话
    // 实现用户的redis会话
    UsersVO usersVO = conventUsersVO(userResult);

    CookieUtils.setCookie(request, response, "user",
        JsonUtils.objectToJson(usersVO), true);

    // TODO 同步购物车数据
    synchShopcartData(userResult.getId(),request, response);

    return IMOOCJSONResult.ok(usersVO);
  }

  private Users setNullProperty(Users userResult) {
    userResult.setPassword(null);
    userResult.setMobile(null);
    userResult.setEmail(null);
    userResult.setCreatedTime(null);
    userResult.setUpdatedTime(null);
    userResult.setBirthday(null);
    return userResult;
  }

  @ApiOperation(value = "用户退出登录", notes = "用户退出登录", httpMethod = "POST")
  @PostMapping("/logout")
  public IMOOCJSONResult logout(@RequestParam String userId, HttpServletRequest request,
      HttpServletResponse response) {

    //清除用户相关信息的cookie
    CookieUtils.deleteCookie(request, response, "user");

    // TODO 用户退出登录， 清除redis中的user信息
    redisOperator.del(REDIS_USER_TOKEN + ":" + userId);

    // 分布式会话中需要清除用户数据
    CookieUtils.deleteCookie(request, response, FOODIE_SHOPCART);

    return IMOOCJSONResult.ok();

  }
}
